JavaScript 五四三 Ep.06 Array.prototype.includes()


Posted by ABow_Chen on 2022-09-29

一、includes() 簡介

  1. 對陣列使用 includes() 方法,會判斷陣列是否包含特定的元素,若包含則回傳 true,若無則回傳 false。

二、includes() 語法

arr.includes(searchElement[, fromIndex])

searchElement: 要搜尋的元素。

fromIndex(選擇性):

  • 要從此陣列開始搜尋 searchElement 的索引位置,預設為 0。
  • 如果為負數,則會先運算 arr.length + fromIndex 所得到的數值,如果數值為正數,則會當成 fromIndex 開始搜尋是否有 searchElement。
  • 承上,如果計算結果小於 0,則會搜尋整個陣列。

語法的執行範例如下:

const arr = [1, 3, 5, 7, 9];
console.log(arr.includes(2)); // false
console.log(arr.includes(5,2)); // true, 從索引位置 2 開始尋找 5

三、includes() 常見用法、情境

  1. 查找陣列中是否有符合條件的元素

     const dogsColor = ['white', 'black', 'gray'];
     console.log(dogsColor.includes('white')); // true
     console.log(dogsColor.includes('brown')); // false
     console.log(dogsColor.includes('ack')); // false, 字串沒有完全相同會回傳 false
    
  2. fromIndex 大於或等於陣列長度

     const dogsColor = ['white', 'black', 'gray'];
     console.log(dogsColor.includes('white',3)); // false,等於陣列長度
     console.log(dogsColor.includes('white',6)); // false,大於陣列長度
    
  3. fromIndex 小於 0 的情況

     const dogsColor = ['white', 'black', 'gray'];
     console.log(dogsColor.includes('white',-1)); 
     // false,會先用陣列長度 3 + (-1)(fromIndex) = 2,如果運算結果是正數,則會將此數值當成 fromIndex 來搜尋 searchElement
     console.log(dogsColor.includes('white',-100)); 
     // true,運算結果 3 + (-100) = -97,結果 < 0,則會搜尋整個陣列內容
    

參考資料:

https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

https://ithelp.ithome.com.tw/articles/10238101


#javascript #includes







Related Posts

Training with Different Image Shapes

Training with Different Image Shapes

1338. Reduce Array Size to The Half

1338. Reduce Array Size to The Half

JS 設定預設值 (Default Parameters)

JS 設定預設值 (Default Parameters)


Comments